<template>
<div>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
     v-dialogDrag
    :visible.sync="visible">
    <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
             label-width="120px">
      <el-row  :gutter="15">
        <el-col :span="12">
            <el-form-item label="设备名称" prop="name"
                :rules="[
                 ]">
              <!-- <el-input v-show="method === 'add'" v-model="inputForm.partDevice.id" placeholder="请填写设备名称" disabled=""></el-input> -->
              <el-input  v-model="names" placeholder="请填写设备名称" disabled=""></el-input>
              </el-form-item>
        </el-col>
        <el-col :span="12">
            <!-- <el-form-item label="部件" prop="units" -->
            <!-- trigger:'blur' 是失去焦点时候触发 -->
            <el-form-item label="部件名称" prop="units" :rules="[{required: true, message:'部件不能为空', trigger:'blur'}]">
             <el-select v-model="inputForm.units" placeholder="请选择部件" style="width:100%;" v-loading = 'isOneDropDownBoxLoading' :disabled=isOneDropDownBoxLoading>
              <el-option v-for="item in inputForm.partsData" :key="item.id" :label="'[' + item.code + ']' +item.name" :value="item.id" ref="units"></el-option>
             </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <!-- <el-form-item label="零件名称" prop="part" -->
            <el-form-item label="零件名称" prop="part" :rules="[]" >
             <el-select v-model="inputForm.part" placeholder="请选择零件名称" style="width:100%;" v-loading = 'isTwoDropDownBoxLoading' :disabled=isTwoDropDownBoxLoading>
               <el-option v-for="item in inputForm.componentData" :key="item.id" :label= "'[' + ']' +item.name" :value="item.id" ref="part"></el-option>
             </el-select>
             </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="材质" prop="texture"
                :rules="[
                 ]">
              <el-input v-model="inputForm.texture" placeholder="请填写材质"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="24">
            <el-form-item label="结构图上传" prop="pic"
                :rules="[
                  {required: true, message:'结构图不能为空', trigger:'blur'}
                 ]">
              <el-upload ref="pic"
              v-if="visible"
              list-type="picture-card"
                    :action="`${this.$http.BASE_URL}/sys/file/webupload/upload?uploadPath=/basicdata/standard/basicdataRepair`"
                    :headers="{token: $cookie.get('token')}"
                    :on-preview="(file, fileList) => {
                        $alert(`<img style='width:100%' src=' ${(file.response && file.response.url) || file.url}'/>`,  {
                          dangerouslyUseHTMLString: true,
                          showConfirmButton: false,
                          closeOnClickModal: true,
                          customClass: 'showPic'
                        });
                    }"
                    :on-success="(response, file, fileList) => {
                       inputForm.pic = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
                    }"
                    :on-remove="(file, fileList) => {
                      $http.post(`/sys/file/webupload/deleteByUrl?url=${(file.response && file.response.url) || file.url}`).then(({data}) => {
                        $message.success(data.msg)
                      })
                      inputForm.pic = fileList.map(item => item.url).join('|')
                    }"
                    :before-remove="(file, fileList) => {
                      return $confirm(`确定删除 ${file.name}？`)
                    }"
                    multiple
                    :limit="1"
                    :on-exceed="(files, fileList) =>{
                      $message.warning(`当前限制选择 1 个图片，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个图片`)
                    }"
                    :file-list="picArra">
                    <i class="el-icon-plus"></i>
                  </el-upload>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="图面尺寸" prop="picSize"
                :rules="[
                 ]">
              <el-input v-model="inputForm.picSize" placeholder="请填写图面尺寸"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="图面间隙" prop="picGap"
                :rules="[
                 ]">
              <el-input v-model="inputForm.picGap" placeholder="请填写图面间隙"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="允许值" prop="allowValue"
                :rules="[
                 ]">
              <el-input v-model="inputForm.allowValue" placeholder="请填写允许值"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="方法" prop="method"
                :rules="[
                 ]">
              <!-- <el-input v-model="inputForm.method" placeholder="请填写方法"     ></el-input> -->
              <el-select v-model="inputForm.method" placeholder="请选择方法"  style="width:100%;">
                <el-option v-for="method in $dictUtils.getDictList('basicdata_repair_method')" :label="method.label" :value="method.value" :key="method.value" ></el-option>
              </el-select>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="周期" prop="cycle"
                :rules="[
                 ]">
              <!-- <el-input v-model="inputForm.cycle" placeholder="请填写周期"     ></el-input> -->
              <!-- :disabled = "iscycleUnitAccoding" -->
               <el-input-number v-model="inputForm.cycleUnitValue" :min="0" :max="100" label="描述文字"  v-loading = 'iscycleUnit'  style="width:80%;"></el-input-number>
               <el-select v-model="inputForm.cycleData" placeholder="请选择周期单位" @change="handleChangeCycle" style="width:20%;" >
                 <el-option v-for="cycleData in $dictUtils.getDictList('basticdata_repair_standard_date')" :label="cycleData.label" :value="cycleData.value" :key="cycleData.value" ref="part"></el-option>
               </el-select>
           </el-form-item>
        </el-col>
        <!-- <el-col :span="12"> -->
            <!-- <el-form-item label="零件名称" prop="part" -->
            <!-- <el-form-item label="周期单位" prop="cycleUnit" :rules="[]" > -->
             <!-- </el-form-item> -->
        <!-- </el-col> -->
        <el-col :span="12">
            <el-form-item label="更换周期" prop="changeCycle"
                :rules="[
                 ]">
              <!-- <el-input v-model="inputForm.changeCycle" placeholder="请填写更换周期"     ></el-input> -->
              <!-- :disabled = "isreplacecycleUnitAccoding" -->
              <el-input-number v-model="inputForm.replacecycleUnitValue" :min="0" :max="100" label="描述文字"  v-loading = 'isreplacecycleUnit'  style="width:80%;"></el-input-number>
              <el-select v-model="inputForm.changeCycleData" placeholder="请选择周期单位" @change="handleChangereplacecycle" style="width:20%;" >
                <el-option v-for="changeCycleData in $dictUtils.getDictList('basticdata_repair_standard_date')" :label="changeCycleData.label" :value="changeCycleData.value" :key="changeCycleData.value" ref="units" ></el-option>
              </el-select>
           </el-form-item>
        </el-col>
        <!-- <el-col :span="12"> -->
            <!-- <el-form-item label="零件名称" prop="part" -->
            <!-- <el-form-item label="更换周期单位" prop="replaceCycleUnit" :rules="[]" > -->
             <!-- </el-form-item> -->
        <!-- </el-col> -->
        <el-col :span="12">
            <el-form-item label="备注" prop="remarks"
                :rules="[
                 ]">
          <el-input type="textarea" v-model="inputForm.remarks" placeholder="请填写备注"     ></el-input>
           </el-form-item>
        </el-col>
        </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close()">关闭</el-button>
      <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
  export default {
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        inputForm: {
          partDevice: {
            id: '',
            code: ''
          },
          id: '',
          name: '',
          units: '', // 首级下拉框四级数据prop
          part: '', // 次级下拉框五级数据prop
          texture: '', // 材质
          picSize: '', // 图面尺寸
          picGap: '', // 图面间隙
          allowValue: '', // 允许值
          method: '', // 新建，查看，修改状态
          cycle: '', // 周期
          changeCycle: '', // 更换周期
          remarks: '', // 备注信息
          partsData: [], // 部件数据
          componentData: [], // 零件数据
          cycleData: [], // 周期单位
          changeCycleData: [], // 更换周期单位
          cycleUnitValue: '', // 周期值
          replacecycleUnitValue: '', // 更换周期值
          pic: '', // 图面上传
          unitName: '' // 零件名称
        },
        fileDevicename: '', // 设备名称
        countMax: 100, // 周期计数器最大值
        countreplaceMax: 100, // 更换周期计数器最大值
        parts: '', // 首级下拉框prop
        component: '', // 子级下拉框prop
        isOneDropDownBoxLoading: false, // 判断一级下拉框是否正在加载数据
        isTwoDropDownBoxLoading: false, // 判断二级下拉框是否正在加载数据
        iscycleUnit: false, // 判断计数器是否正在加载数据
        iscycleUnitAccoding: true, // 计数器显隐
        isreplacecycleUnit: false, // 判断计数器是否正在加载数据
        isreplacecycleUnitAccoding: true, // 计数器显隐
        picArra: [], // 图片存储
        countOne: 0, // 周期点击
        countTwo: 0, // 更换周期点击
        countfirst: 0, // 首次加载的二级下拉框置空判断
        conversion: '', //转化处理
        names: '' // 设备名称
      }
    },
    watch: {
      // 监测设备名称编号变化(监听某个对象里面的某个固定属性时候所用如inputForm.partDevice.id)
      // 深度监听
      'inputForm.partDevice.id': function (newVal, oldVal) {
        this.getNextNode(newVal)
      },
      // 监测首级下拉框变化
      'inputForm.units': function (newVal, oldVal) {
        if (this.isOneDropDownBoxLoading === true) {
         this.isOneDropDownBoxLoading = false
        }
        if (newVal !== '') {
        this.dropDownBoxAssociated(newVal)
        }
      },
      'inputForm.part': function (newVal, oldVal) {
          this.productTypeReturn(newVal)
      }
    },
    components: {
    },
    methods: {
      // 发送油品型号方法返回油品型号
      productTypeReturn (id) {
        this.$http({
          url: `/basicdata/basictree/partDeviceNode/queryById?id=${id}`,
          method: 'get'
        }).then(({ data }) => {
          this.inputForm.unitName = data.partDeviceNode.name
        })
      },
      // 判断周期点击
      handleChangeCycle (val) {
        this.countOne = 1
      },
      // 判断更换周期点击
      handleChangereplacecycle (val) {
        this.countTwo = 1
      },
      // 获取下一层级节点
      // 需要传入想要获取下一级树的数据的父级id参数（比如传三级id此方法获取4级数据）
      getNextNode (presentNode) {
        this.isOneDropDownBoxLoading = true
        this.$http({
          url: `/basicdata/basictree/partDeviceNode/nextLevelTreeData`,
          method: 'get',
          params: {
            id: presentNode
          }
        }).then(({ data }) => {
          this.inputForm.partsData = data.data
          this.isOneDropDownBoxLoading = false
        })
      },
      // 关闭触发的方法
      close () {
        this.visible = false
        this.countfirst = 0
      },
      // 暂时的初始化方法处理（后期会改进）
      dataInitialize () {
        this.inputForm.componentData = ''
        this.inputForm.method = ''
        this.countfirst = 0
        this.countOne = 0
        this.countTwo = 0
        this.inputForm.units = ''
        this.inputForm.part = ''
        this.iscycleUnitAccoding = true //将计数器设置为不可选中
        this.isreplacecycleUnitAccoding = true
        this.inputForm.changeCycleData = 'D'
        this.inputForm.cycleData = 'D'
        this.inputForm.replacecycleUnitValue = 0
        this.inputForm.cycleUnitValue = 0
      },
      // 链接List的主要接口 ，新建，修改，查看时候会调用
      init (method, id, partDevice) {
        this.names = '[' + partDevice.code + ']' + partDevice.name
        this.inputForm.partDevice.id = partDevice.id
        this.fileDevicename = partDevice.name
        this.method = method
        this.inputForm.id = id
        this.dataInitialize()
        // this.parts = '' // 首级下拉框prop做清空处理
        // this.component = '' // 子级下拉框prop做清空处理
        if (method === 'add') {
          this.title = `新建设备维修技术标准`
        } else if (method === 'edit') {
          this.title = '修改设备维修技术标准'
        } else if (method === 'view') {
          this.title = '查看设备维修技术标准'
        }
        this.picArra = []
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.inputForm.partDevice.id = partDevice.id
          this.$refs.inputForm.resetFields()
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.$http({
              url: `/basicdata/standard/basicdataRepair/queryById?id=${this.inputForm.id}`,
              method: 'get'
            }).then(({data}) => {
              this.inputForm = this.recover(this.inputForm, data.basicdataRepair)
              this.inputForm.pic.split('|').forEach((item) => {
                if (item.trim().length > 0) {
                  this.picArra.push({name: decodeURIComponent(item.substring(item.lastIndexOf('/') + 1)), url: item})
                }
              })
              this.inputForm.name = '[' + partDevice.code + ']' + this.inputForm.name
              this.getNextNode(partDevice.id)
              this.loading = false
            })
          }
        })
      },
      // 二级下拉框与一级下拉框关联方法(传的参数是一级下拉框的id值)
      dropDownBoxAssociated (newVal) {
        this.isTwoDropDownBoxLoading = true
        if (this.countfirst >= 1) {
          // this.component = ''
          this.inputForm.part = ''
        } else {
          this.countfirst = this.countfirst + 1
        }
        console.log(this.countfirst)
        this.$http({
          url: `/basicdata/basictree/partDeviceNode/nextLevelTreeData`,
          method: 'get',
          params: {
            id: newVal
          }
        }).then(({ data }) => {
          this.inputForm.componentData = data.data
          this.isTwoDropDownBoxLoading = false
        })
      },
      // 表单提交时候的名称转化，以及拼接
      converSion () {
        this.inputForm.name = this.fileDevicename
        this.inputForm.cycle = this.inputForm.cycleUnitValue + this.inputForm.cycleData + ''
        this.inputForm.changeCycle = this.inputForm.replacecycleUnitValue + this.inputForm.changeCycleData + ''
        this.countfirst = 0
      },
      // 表单提交
      doSubmit () {
        this.converSion()
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: `/basicdata/standard/basicdataRepair/save`,
              method: 'post',
              data: this.inputForm
            }).then(({data}) => {
              if (data && data.success) {
                this.visible = false
                this.$message.success(data.msg)
                this.$emit('refreshDataList')
              }
              this.loading = false
            })
          }
        })
      }
    }
  }
</script>
